﻿var Account = new function () {
    'use strict';

    this.onLoginSuccess = function (el, data, xhr) {
        if (data) {
            app.cache.global.set('user', data);
        }

        location.href = "/Home/Index";
    }

    this.onResetPassword = function (el, data, xhr) {
        location.href = "/Account/Login";
    }

    this.onLogout = function () {
        $.api.get({
            action: 'onLink',
            url: '/Account/Logout',
            complete: function () {
                localStorage.clear();
                location.href = "/Account/Login"
            }
        });
    };
}

var Common = new function () {

    /**
     * 年龄格式化显示
     * @param {any} el
     */
    this.ageFormatter = el => (el.options.value || 0) + ' 岁';
    /**
     * 人数格式化显示
     * @param {any} el
     */
    this.peopleCountFormatter = el => (el.options.value || 0) + ' 个';

    this.boundBusinessKey = el => {
        let $form = el.$from;
        if ($.com.isJqueryObject($form)) {
            let form = $form.data(_config_.form.namespace);
            if ($.com.hasValue(form)) {
                let id = form.getValue('data.Id');
                if ($.com.hasValue(id)) {
                    el.$fields.filter('[data-field="BusinessKey"]').val(id);
                }
            }
        }
    }
    /**
     * 比例格式化显示
     * @param {any} el
     */
    this.inputPercentFormatter = el => $.com.percentFormatter(el.options.value);
    /**
     * 面积格式化显示
     * @param {any} el
     */
    this.inputAreaFormatter = el => $.com.areaFormatter(el.options.value);

    /**
     * 添加 Additional form 的方法
     * @param {any} el
     */
    this.onAddAdditional = el => {
        if ($.com.hasValue(el.options) && $.com.hasValue(el.options.data) && !$.com.hasValue(el.options.data.Index)) {
            let index = 1;
            if ($.com.isJqueryObject(el.$form)) {
                let form = el.$form.data(_config_.form.namespace);
                if ($.com.hasValue(form)) {
                    if (form.options.type === _config_.default.arrayTypeName && $.com.isArray(form.options.data)) {
                        let length = (form.options.data.length > 2) ? form.options.data.length : 2;
                        index = Number(form.options.data[length - 2].Index || 0) + 1;
                    }
                }
            }

            el.options.data.Index = index;
        }
    };

    /**
     * 通过 assignType 和 id 获取对应的 identity.name
     * @param {any} assignType
     * @param {any} id
     */
    this.getByAssignType = (assignType, id) => $.com.commonFormatter(app.cache.assignType, assignType);
}

var GetTree = new function () {
    this.onTreeLoadCheck = el => {
        onBuildingChange(el, true);
    };

    this.onTreeLoad = el => {
        onBuildingChange(el, false);
    };

    function onBuildingChange(el, getCheck) {
        let $form = el.$form;
        var $tree = el.$form.find('[data-toggle="tree"]');
        if ($.com.isJqueryObject($form) && $.com.isJqueryObject($tree)) {
            $tree.parent().height($form.find('.form-body').height());
            let form = $form.data(_config_.form.namespace);
            if ($.com.hasValue(form)) {
                let formData = form.getValue('data');
                if ($.com.hasValue(formData) && $.com.hasValue(formData.Building)) {
                    building = formData.Building;
                    if ($.com.hasValue(building.Id)) {
                        $.api.get("/odata/Houses?$filter= BuildingId eq '" + building.Id + "'", data => {
                            //选中house绑定
                            var tree = $tree.data("kendoTreeView");
                            var treeNodes = generateBuildingNode(data, building, getCheck);
                            if ($.com.hasValue(tree)) {
                                tree.setDataSource(treeNodes);
                            } else {
                                var options = $.extend({
                                    check: onCheck,
                                    dataSource: treeNodes
                                }, $tree.data());
                                tree = $tree.kendoTreeView(options).data("kendoTreeView");
                            }

                            if (getCheck) {
                                initSetChecked(formData, tree);
                            }
                        });
                    }
                }
            }
        }
    };


    function initSetChecked(data, treeView) {
        if ($.com.hasValue(data) && $.com.hasValue(data.Id)) {
            $.api.get("/odata/ApportionDetailRecords?$filter=ProjectDetailId eq '" + data.Id + "'", data => {
                if ($.isArray(data) && data.length > 0) {
                    var apportionRecordIds = [];//data.select('ApportionRecordId');
                    data.forEach(a => { apportionRecordIds.push(String(a["ApportionRecordId"])) })
                    // todo 查询拼接in条件
                    if ($.isArray(apportionRecordIds) && apportionRecordIds.length > 0) {
                        $.api.get("/odata/ApportionRecords?$filter=Id in ('151174121579872256','144291685390614528')", houses => {
                            houseIds = houses.select('HouseId');
                            var nodes = treeView.dataSource.view();
                            var houseNodes = [];
                            getTreeNodes(nodes, houseNodes, houseIds);
                            $.each(houseNodes, function (i, x) {
                                x.set("checked", true);
                                //   treeView.expand(treeView.findByUid(x.uid));//设置展开节点
                            });

                        });

                    }
                }
            });
        }
    }

    function getTreeNodes(node, houseNodes, houseIds) {
        for (var i = 0; i < node.length; i++) {
            if (node[i].hasChildren) {
                getTreeNodes(node[i].children.view(), houseNodes, houseIds);
                continue;
            }

            if (node[i].id.indexOf('#') < 0 && houseIds.indexOf(node[i].id) >= 0) {
                houseNodes.push(node[i]);
            }
        }
    };


    //BuildingNode
    function generateBuildingNode(housesList, building, getCheck) {
        //生成单元
        if (!$.com.isNullOrEmpty(building)) {
            var treeNodes = { id: '##', text: building.Name, items: [], expanded: true };
            if ($.isNumeric(building.UnitCount) && building.UnitCount > 0) {
                for (var i = 1; i <= building.UnitCount; i++) {
                    var unit = { id: '#' + i, text: i + '单元', items: [], expanded: true, Unit: i };
                    //生成层
                    if ($.isNumeric(building.MaxFloor) && $.isNumeric(building.MinFloor)) {
                        for (var j = building.MinFloor; j <= building.MaxFloor; j++) {
                            var floor = { id: '#' + i + '#' + j, text: j + '层', items: [], expanded: getCheck, Unit: i, Floor: j };
                            //生成分户
                            var houses = housesList.where(function (x) { return x.Unit == i && x.Floor == j; });
                            if (!$.com.isNullOrEmpty(houses)) {
                                floor = generateHouseNode(floor, houses);
                            }
                            unit.items.push(floor);
                        }
                        treeNodes.items.push(unit);
                    }
                }
            }
        }

        return [treeNodes];
    };

    //HouseNode
    function generateHouseNode(floor, houses) {

        if (!$.com.isNullOrEmpty(floor) && $.isArray(houses) && houses.length > 0) {
            floor.items = [];
            houses.sort(function (a, b) { return a.Name > b.Name; });
            $.each(houses, function (i, x) {
                x.id = x.Id;
                x.text = x.Name;
                floor.items.push(x);
            });
        }
        return floor;
    };
    //选中项获取
    function checkedNodeIds(node, checkedNodes) {
        for (var i = 0; i < node.length; i++) {
            if (node[i].checked) {
                checkedNodes.push(node[i]);
            }

            if (node[i].hasChildren) {
                checkedNodeIds(node[i].children.view(), checkedNodes);
            }
        }
    };


    //绑定分摊范围ids
    function autoApportionRange(model, checkedNodeList) {

        var apportionRange = '';
        var community = model.find('[data-field="Project.Community.Name"]').val();
        if ($.com.hasValue(community)) {
            apportionRange = community;
        }
        var building = model.find('[data-field="Building.Name"]').val();
        if ($.com.hasValue(building)) {
            apportionRange += '->' + building;
            var result = getApportionRangeDetail(checkedNodeList);
            if ($.com.hasValue(result)) {
                apportionRange += '->' + result;
            }
        }

        model.find('[data-field="ApportionRange"]').val(apportionRange).change();
    };

    //get(ApportionRange)
    function getApportionRangeDetail(checkedNodeList) {
        var nodes = [];
        if (checkedNodeList.length > 0) { nodes = checkedNodeList; }
        var nodes = nodes.where(function (x) { return x.id.indexOf('#') >= 0; });
        if ($.isArray(nodes) && nodes.length != 0) {
            var apportionRange = '';
            //如果选中了building, 则返回null,
            if (nodes.exist(function (x) { return x.id == '##'; })) {
                apportionRange = '整幢楼';
            } else {
                //如果选中了部分单元, 先处理单元
                var units = nodes.where(function (x) { return x.id.lastIndexOf('#') == 0; }) || [];
                if ($.isArray(units) && units.length > 0) {
                    units = units.sort(function (x, y) { return (x.id >= y.id) ? 1 : -1; });
                    apportionRange = units.select('text').join(',');
                }
                //在处理剩下的层
                nodes = nodes.where(function (x) {
                    return x.id != '##' && x.id.lastIndexOf('#') > 0 && !units.exist(function (u) {
                        return u.id == x.parent;
                    });
                });
                if ($.isArray(nodes) && nodes.length > 0) {
                    if ($.com.hasValue(apportionRange)) {
                        apportionRange += ',';
                    }

                    nodes = nodes.sort(function (x, y) { return (x.id >= y.id) ? 1 : -1; });
                    var unit = '';
                    $.each(nodes, function (i, x) {
                        var unitX = x["Unit"];
                        if (unitX != unit) {
                            if (unit == '') {
                                unit = unitX;
                                apportionRange += unit + '单元(';
                            } else {
                                unit = unitX;
                                apportionRange += '),' + unit + '单元(';
                            }
                        }
                        apportionRange += x.text + ',';
                    });
                    if (apportionRange.endsWith(',')) {
                        apportionRange = apportionRange.substr(0, apportionRange.length - 1);
                    }
                    apportionRange += ')';
                    apportionRange = apportionRange.replace(/\,\)/g, ')');
                }
            }

            return apportionRange;
        }
    };

    function onCheck(el) {
        var $tree = $(el.sender.element);
        var checkedNodeList = [],
            nodes = $tree.data("kendoTreeView").dataSource.view();
        checkedNodeIds(nodes, checkedNodeList);
        //HouseIds绑定
        let $form = $tree.closest(_config_.selector.form);
        var houses = checkedNodeList.where(function (x) { return x.id.indexOf('#') < 0; });
        var houseIdStrs = "";
        if ($.isArray(houses) && houses.length > 0) {
            var houseIds = houses.select('id');
            if ($.isArray(houseIds) && houseIds.length > 0) {
                houseIdStrs = houseIds.join(',')
            }
        }

        $form.find('[data-field="HouseIds"]').val(houseIdStrs).change();
        //ApportionRange绑定
        autoApportionRange($form, checkedNodeList);
    };

}

var PrintPDF = new function () {
    this.onClickPrintPMRV = el => {
        //物业维修资金备案凭证
        pdfView(el, null, "PropertyMaintenanceRecordVoucher");

    }

    this.onClickPrintAPN = el => {
        //打印预付款拨款通知书
        pdfView(el, null, "AdvancePaymentNotice");
    };

    this.onClickPrintHMFAN = el => {
        debugger
        //打印拨款通知书
        pdfView(el, null, "HouseMaintenanceFundAppropriationNotice");
    };
    this.onClickPrintPN = el => {
        //缴费通知单
        pdfView(el, null, "PaymentNotice");

    }
    this.onClickPrintTP = Id => {
        debugger
        pdfView(null, Id, "TransferProprietor");
    }
    function pdfView(el, Id, name) {
        if (!$.com.isNullOrEmpty(el)) {
            var $form = $(el.currentTarget).closest(_config_.selector.form)
            if (!$.com.isNullOrEmpty($form)) {
                var form = $form.data(_config_.form.namespace);
                var data = form.options.data;
                if (!$.com.isNullOrEmpty(data) && $.com.hasValue(data.Id)) {
                    Id = data.Id
                }
            }
        }

        if ($.com.hasValue(Id)) {
            var url = "https://localhost:8443/api/BaseProjects/PrintPdf?Name=" + name + "&&Id=" + Id;
            var link = $('<a href="/lib/pdfjs/web/viewer.html?file=' + encodeURIComponent(url) + '" target="_blank"></a>');
            link.get(0).click();
        }
    }
}
